package com.baykalcakici.cafepicker.tasks;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.baykalcakici.cafepicker.Main;
import com.baykalcakici.cafepicker.picker.CafePicker;
import com.baykalcakici.cafepicker.util.FtClient;
import com.google.common.base.Preconditions;

/**
 * Task responsible of loading the user account and initializing the CafePicker.
 */
public class LoginTask extends AsyncTask<String, Integer, String> {
  private ProgressDialog dialog;
  private Context context;

  public LoginTask(ProgressDialog dialog, Context context) {
    this.dialog = Preconditions.checkNotNull(dialog);
    this.context = Preconditions.checkNotNull(context);
  }

  @Override
  protected String doInBackground(String... params) {
    AccountManager accountMgr = AccountManager.get(context);
    Account[] accounts = accountMgr.getAccountsByType("com.google");
    for (Account account : accounts) {
      Log.d("cafepicker", account.toString());
    }
    if (accounts.length != 0) {
      // Currently always use the first Google account on the phone.
      AccountManagerFuture<Bundle> bundle =
          accountMgr.getAuthToken(accounts[0], "fusiontables", true, new GetAuthTokenCallback(),
              null);
      try {
        String token = bundle.getResult().getString(AccountManager.KEY_AUTHTOKEN);
        Log.d("cafepicker", "Token is: " + token);
        Main.cafePicker = new CafePicker(new FtClient(token));
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return null;
  }

  @Override
  protected void onPostExecute(String param) {
    super.onPostExecute(param);
    dialog.dismiss();
  }

  private class GetAuthTokenCallback implements AccountManagerCallback<Bundle> {
    @Override
    public void run(AccountManagerFuture<Bundle> arg0) {
      Bundle bundle;
      try {
        bundle = arg0.getResult();
        Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
        if (intent != null) {
          Log.d("cafepicker", "Picking an account");
          context.startActivity(intent);
        }
      } catch (Exception e) {
        Log.d("cafepicker", "Error while loading AccountManagerFuture result");
      }
    }
  }
}
